package com.situ.onlinebookstore.front.service.impl;

import com.situ.onlinebookstore.common.entity.Addr;
import com.situ.onlinebookstore.common.mapper.AddrMapper;
import com.situ.onlinebookstore.front.service.AddrService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AddrServiceImpl implements AddrService {
    private final AddrMapper addrMapper;

    @Override
    public int add(Addr addr) throws Exception {
        //一个用户最多只能有3个地址
        List list = getByUserId(addr.getUserId());
        if (list.size() >= 3) {
            throw new Exception("最多只能有3个地址！");
        }
        return addrMapper.insert(addr);
    }

    @Override
    public int remove(Addr addr) throws Exception {
        Addr sAddr = addrMapper.selectById(addr.getId());
        if (ObjectUtils.isEmpty(sAddr)){
            throw new Exception("无效地址");
        }
        if (!addr.getUserId().equals(sAddr.getUserId())){
            throw new Exception("无权编辑的地址!");
        }
        return addrMapper.delete(addr.getId());
    }

    @Override
    public int edit(Addr addr) throws Exception {
        Addr sAddr = addrMapper.selectById(addr.getId());
        if (ObjectUtils.isEmpty(sAddr)){
            throw new Exception("无效地址");
        }
        if (!addr.getUserId().equals(sAddr.getUserId())){
            throw new Exception("无权编辑的地址!");
        }
        //最多只能有一个默认地址
        if (addr.getStatus()==1) {
            List<Addr> list = getByUserId(addr.getUserId());
            list.forEach((address)->{
                if (address.getStatus()==1){
                    address.setStatus(0);
                    addrMapper.update(address);
                }
            });
        }
        return addrMapper.update(addr);
    }

    @Override
    public Addr getById(Integer id) {
        return addrMapper.selectById(id);
    }

    @Override
    public List<Addr> getByUserId(Integer userId) {
        return addrMapper.selectByUserId(userId);
    }
}
